<template>
  <input
    ref="input"
    :class="eventName"
    @keydown="keydown"
    @input="input"
    @keyup="$emit('keyup')"
    @focus="
      $emit('focus');
      eventName = 'focus';
    "
    @blur="
      $emit('blur');
      eventName = 'blur';
    "
    :type="type"
    :value="$value"
    :placeholder="placeholder"
  />
</template>

<script>
export default {
  props: {
    //最大值
    max: {
      type: Number | Boolean | String,
      default: false
    },
    //小数位
    decimal: {
      type: Number | Boolean | String,
      default: false
    },
    type: {
      type: String,
      default: "text"
    },
    placeholder: {
      type: String,
      default: ""
    },
    value: {
      type: String | Number | Boolean,
      default: ""
    }
  },
  data() {
    return {
      old: "",
      eventName: ""
    };
  },
  computed: {
    $value() {
      if (this.type === "text" && typeof this.value === "object")
        return JSON.stringify(this.value);
      if (this.type === "number") {
        if (this.max !== false && this.value > Number(this.max)) {
          return this.max;
        }
      }
      return this.value;
    }
  },
  methods: {
    keydown() {
      this.old = this.$refs.input.value;
      this.$emit("keydown");
    },
    input() {
      if (this.type === "number") {
        this.checkNumber();
      }
      this.emitInput();
    },
    checkNumber() {
      let value = this.$refs.input.value;
      //最大输入值限制
      if (this.max !== false && value > Number(this.max)) {
        value = this.old;
        this.emitWarn();
      }
      //防止输入“00”
      if (value.indexOf(".") === -1 && value !== "") {
        if (Number(value) === 0 && value !== "0") {
          value = this.old;
        }
      }
      //精度小数位限制
      if (this.decimal !== false) {
        let length = value.split(".")[1] ? value.split(".")[1].length : 0;
        if (length > Number(this.decimal)) {
          value = this.old;
          this.$emit("inputwarn", { decimal: this.decimal });
        }
      }
      this.$refs.input.value = value;
    },
    emitWarn() {
      this.$emit("inputwarn", { max: this.max });
    },
    emitInput() {
      this.$emit("input");
    }
  }
};
</script>

<style>
input {
  outline: none;
}
</style>
